/**
 * 数据库设计器
 */
//字段默认值
var filedDefaultArr = [
	{
		'tableName': '设计',
		'field': 'defaultField',
		'fieldCh': '系统预制字段',
		'type': '',
		'children': []
	}
];
//跳转到数据库设计器时得到缓存中的数据
var sqlData = localStorage.getItem("sqlData");
var sqlDataObj = JSON.parse(sqlData);
var modelId = sqlDataObj.id;

mini.parse();
//路径前缀
var url = bootPATH + "../frame/frame1/pages/";  
//获得数据表
var tableTreeGrid = mini.get("tableTreeGrid");
var filedTreegrid = mini.get('filedTreegrid');
var editWindow = mini.get("editWindow");
var defaultField = 0;		//字段默认号
//布局高度
mini.get("sp").set({
	height : document.body.clientHeight - 10
});
//初始化
$(function(){
	//通过模型id查询该模型下的表
	httpModelTable(modelId);
	//表的默认字段
	//httpFiledDefault();
});
//选中表时显示该表的字段
function onNodeselectMo(e){
	var records = tableTreeGrid.getSelectedNode();
    //var record = tableTreeGrid.getSelected();
	//每次赋空
	filedDefaultArr[0].children = [];
    if (records) {
    	var tableClassId = records.tableClassId;
        var tableClassName = records.tableClassName;
        //请求表详细信息
        $.ajax({
            url: ajaxUrl + "/classTable/findByTableId.do?tableClassId=" + tableClassId,
            type: "post",
            //dataType: "json",
            traditional: true,
            success: function(data) {
                if(data.message == 'success'){
                	//请求到的默认字段
                	 var filedData = data.data;
                	 var filedVal = filedData;
                	 //本地显示默认字段标题
                	 var defChildData = filedDefaultArr[0].children;
                     if(filedData.length > 0){
                    	 //将请求到的默认字段添加到本地的children中
                    	 filedData.forEach(function(item,index){
                    		 if(item.state == '1'){
                    			 item.state = '是';
                    			 //添加到默认字段中
                    			 defChildData.push(item);
                    		 }else{
                    			 item.state = '否';
                    		 }
                    		 //是否可为空显示
                    		 item.notNull = item.notNull == 'true' ? '可为空':'不可为空';
                    	 });
                    	 //删除
                    	 var i = filedData.length;
                    	 while(i--){
                    		 if(filedData[i].state == '是'){
                    			 filedData.splice(i,1);
                    		 }
                    	 }
                    	 filedData.unshift(filedDefaultArr[0]);
                    	//字段表赋值
                     	filedTreegrid.setData(filedData);
                     	//取得所有默认英文字段名中的最大号
                     	var numArr = [];
                     	filedData.forEach(function(item,index){
                     		var fieldItem = item.field;
                     		//如果存在'xgry'，那么就是系统默认给出的字段名
                     		if(fieldItem.indexOf("xgry") != -1){
                     			var fieldItemArr = fieldItem.split('_');
                     			var len = fieldItemArr.length-1;
                     			var numField = parseInt(fieldItemArr[len]);
                         		numArr.push(numField);
                     		}
                     	});
                     	numArr = numArr.sort(sortNumber);
                     	if(numArr.length > 0){
                     		defaultField = numArr[numArr.length-1];
                     	}else{
                     		defaultField = 0;
                     	}
                     	
                     }else{
                    	//字段表赋值
                      	filedTreegrid.setData([]);
                      	mini.alert('暂无字段');
                     }
                }else{
                	mini.alert('失败');
                }
                
            },
            error : function(data){
                mini.alert('失败');
            }
        });
    }
	
}
//删除数组中某一项，但是不修原数组
function remove(arr, item) {  
	 var result=[];  
	 arr.forEach(function(element){  
	        if(element!=item){  
	            result.push(element);  
	        }  
	});  
	return result;  
}  

//插入子节点（子表）
function onAddNode(e) {
	//得到主表数据（只能给主表添加子表）
	var node = tableTreeGrid.getRow(0);
	//得到所有数据
	var tableData = tableTreeGrid.getData();
	
    //打开新增/编辑表的弹出页面
    mini.open({
        url: url +"sqlDesign/sqlTablePage.html",
        title: "子表", width: 400, height: 160,
        onload: function () {
            var iframe = this.getIFrameEl();

            var data = { 
            		action: "new",
            		parTableClId: node.tableClassId,
            		parClassName: node.tableClassName,
            		model: modelId,
					dbInfoId: node.dbInfo.id
            };
            iframe.contentWindow.SetData(data);
        },
        //子页面关闭时
        ondestroy: function (action) {
        	var iframe = this.getIFrameEl();
            var data = iframe.contentWindow.GetData();
            data = mini.clone(data);    //必须
            if(data.length > 0){
            	var mTableId = node.tableClassId == 0 ? '主表' : '子表';
            	data.forEach(function(item,index){
            		var newNode = {
                        	'mTableId': mTableId,
                        	'tableChClassName': item.tableChClassName,
                        	'tableClassName': item.tableClassName,
                        	'tableClassId': item.tableClassId
                    };
            		tableTreeGrid.addNode(newNode, "add", node);
            	})
            }else{
            	
            }
        }
    });
}

//删除节点（子表）
function onRemoveNode(){
    var node = tableTreeGrid.getSelectedNode();
    if (node) {
    	if(node.mTableId == '子表'){
    		mini.confirm("确定删除选中节点?","系统提示",function(action){
        		if(action == 'ok'){
        			//tableTreeGrid.removeNode(node);
        			var tableName = node.tableClassName;
        			$.ajax({
        			 	 url: ajaxUrl + "/modelClass/deleteTable.do",
        			 	 //url: "http://192.168.31.65:8080/bpm/modelClass/deleteTable.do",
        			     type : "POST",
        			     data: {
        			    	 tableName: tableName
        				 },
        			     success: function(data){
        			     	if(data.state == 'success'){
        			     		showTips();
        			     		//mini.alert(data.message);
        			     		httpModelTable(modelId);
        			     	}else{
        			     		mini.alert(data.message);
        			     	}
        			     },
        			     error: function(data){
        			     	console.log('失败');
        			     }
        			 });
        		}
        	})
        }else{
        	mini.alert('主表不可删除');
        }
    }else{
    	mini.alert('请选择需要删除的子表');
    }
   
}
//右键菜单(对字段的操作)
function onBeforeOpen(e) {
    var menu = e.sender;
            
    var row = tableTreeGrid.getSelected();
    var rowIndex = tableTreeGrid.indexOf(row);    
//    var editItem = mini.getbyName("edit", menu);
//    var removeItem = mini.getbyName("remove", menu);
//    editItem.show();
//    removeItem.enable();

}
//新增字段
function onAddFiled(e) {
	var node = tableTreeGrid.getSelectedNode();
	//var newNode = {};
	//tree.addNode(newNode, "after", node);
	if(node){
		var tableClassId = node.tableClassId;
		var tableClassName = node.tableClassName;
		//生成默认字段
		defaultField++;
		var newField = "xgry_"+(Array(4).join('0') + defaultField).slice(-4);
		//打开新增/编辑字段的弹出页面++++++++++++++++++++++（弹出新增字段页面）
	    mini.open({
	        url: url +"sqlDesign/filePage.html",
	        title: "数据字段", width: 600, height: 330,
	        onload: function () {
	            var iframe = this.getIFrameEl();
	            var data = { 
	            		action: "new",
	            		tableClassId: tableClassId,
	            		tableClassName: tableClassName,
	            		defaultField: newField,
	            		fieldNum: defaultField
	            };
	            iframe.contentWindow.SetData(data);
	        },
	        //子页面关闭时
	        ondestroy: function (action) {
	        	onNodeselectMo();
	        }
	    });
	    //+++++++++++++++++++++++++++++++++++++++++++++++++
	}else{
		mini.alert('请选择表');
	}

}
//编辑字段中文名提交前发生（行内修改时的方法）
function OnCellCommitEdit(e){
	var record = e.record;
	var fieldId = record.tableId;		//字段ID
	var oldValue = e.oldValue;			//旧的值
	var newValue = e.value;				//信修改的值
	 var editTable = {
			 id : fieldId,
			 fieldCh : newValue
	 }
	 var jsonString = JSON.stringify(editTable);
	 //保存编辑
	 $.ajax({
	 	 url: ajaxUrl + "/classTable/updateTable.do",
	 	 //url: "http://192.168.31.65:8080/bpm/classTable/updateTable.do",
	     type : "POST",
	     contentType : "application/json",
	     data: jsonString,
	     success: function(data){
	     	console.log(data,'保存修改成功以后的返回值');
	     },
	     error: function(data){
	     	console.log('失败');
	     }
	 });
}

//删除字段
function onRemove(e) {
	var node = tableTreeGrid.getSelectedNode();
    var row = filedTreegrid.getSelected();
    if (row) {
    	if(row.state == '是'){
    		mini.alert('系统预制字段不可操作');
    	}else{
    		//确定是否删除
        	mini.confirm('确定是否删除该字段','系统提示',function(action){
        		if(action == 'ok'){
        			$.ajax({
        			 	 url: ajaxUrl + "/modelClass/deleteFile.do",
        			 	 //url: "http://192.168.31.65:8080/bpm/modelClass/deleteFile.do",
        			     type : "POST",
        			     //contentType : "application/json",
        			     data: {
        			    	 tableName: node.tableClassName,
        			    	 field: row.field
        				 },
        			     success: function(data){
							 console.log(typeof data);
							 //将保存成功的数据存储
							 saveDataArr.push(addFieldObj);

        			     	//mini.alert(data.message);
        			     	if(data.state == 'success'){
        			     		//删除成功提示
        			     		showTips();
        			     		//重新刷新数据
        			     		onNodeselectMo();
        			     	}else{
        			     		mini.alert(data.message);
        			     	}
        			     },
        			     error: function(data){
        			     	console.log(data);
        			     }
        			 });
        		}
        	})
    	}
    }else{
    	mini.alert('请选择要删除的字段');
    }   
}
//表中文名称可编辑校验（系统预制的字段不可修改）
function OnCellBeginEditTable(e){
	var record = e.record, field = e.field;
    if (field == "tableChClassName" && record.mTableId == 0) {
        e.cancel = true;    
    }
}
//字段中文名称可编辑校验（系统预制的字段不可修改）
function OnCellBeginEdit(e) {
    var record = e.record, field = e.field;
    if (field == "fieldCh" && record.state == "是") {
        e.cancel = true;    
    }
}
//数字数组排序
function sortNumber(a, b){
	return a - b;
}
//通过模型id查询表
function httpModelTable(modelId){
	modelId = modelId + '';
//	var idObj = {
//			id: modelId
//	}
//	console.log(idObj);
//	var idString = JSON.stringify(idObj);
//	//加密
//	idString = encrypt(idString);
	$.ajax({
		 url: ajaxUrl + "/tableClass/findByModelId.do",
		 //url: "http://192.168.11.160:8080/bpm/tableClass/findByModelId.do",
		 type:"post",
		 data: {
			 modelId: modelId
		 },
		 //contentType : "application/utf-8",
		 success: function(data){
			 var tableList = data.data;
			 if(tableList){
				 tableList.forEach(function(item,index){
					 item.mTableId = item.mTableId == 0 ? '主表' : '子表';
				 });
				 //赋值（数据表）
				 //tableTreeGrid.setData(tableList);				//children赋值方式
				 tableTreeGrid.loadList(tableList, "tableClassId", "pid");	//pid赋值方式
			 }else{
				 mini.alert('暂无数据');
			 }
//			 data = data.data;
//			 //解密
//			 var decryptData = decrypt(data);
//			 decryptData = JSON.parse(decryptData);
//			 console.log(decryptData,'返回的表数据');
//			 if(decryptData.state == 'success'){
//				 
//			 }else{
//				 console.log('删除失败');
//			 }
		 },
		 error: function(data){
			 console.log(data);
			 mini.alert('请求失败');
		 }
	})
}


//编辑字段中文名称
function onEditChField(){
	var row = filedTreegrid.getSelected();
    if (row) {
    	if(row.state != '是'){
    		var fieldObj = {
            		id: row.id,
            		fieldCh: row.fieldCh
            }
        	//弹出
            editWindow.show();
            var form = new mini.Form("#editform");
            form.setData(fieldObj);
    	}else{
    		mini.alert('预制字段不可编辑');
    	}
        
    }else{
    	mini.alert('请选择需要编辑的字段');
    }   
	
}
//编辑字段保存(弹窗修改的保存)
function updateChFieldName(){
	//得到需要修改的表单
    var form = new mini.Form("#editform");
    //得到值
    var o = form.getData();
    //var records = tableTreeGrid.getSelectedNode();
    var records = filedTreegrid.getSelected();
    if(o.fieldCh){
    	var editTable = {
    			 id : records.tableId,
    		     fieldCh : o.fieldCh
    	 }
    	 var jsonString = JSON.stringify(editTable);
    	//保存编辑
   	 	$.ajax({
	   		 url: ajaxUrl + "/classTable/updateTable.do",
	   		 //url: "http://192.168.31.65:8080/bpm/classTable/updateTable.do",
	   	     type : "POST",
	   	     contentType : "application/json",
	   	     data: jsonString,
	   	     success: function (data) {
	   	    	 if(data.state == 'success'){
	   	    		 mini.alert(data.message);
	   	    		 //修改成功以后关闭弹出
	   		         editWindow.hide();
	   		         //重新请求字段数据
	   		     	 onNodeselectMo();
	   	    	 }else{
	   	    		 mini.alert(data.message);
	   	    	 }
	   	     },
	   	     error: function (data) {
	   	    	 console.log(data);
	   	     }
   	 	});
    }else{
    	mini.alert('中文字段不可为空');
    }
}
//请求默认字段
function httpFiledDefault(){
	$.ajax({
		 url: ajaxUrl + "/defaultField/findAll.do",
	     type : "POST",
	     //contentType : "application/json",
	     success: function (data) {
	    	 if(data.state == 'success'){
	    		 var defChildFiled = data.data;
	    		 //修改显示内容
	    		 defChildFiled.forEach(function(item,index){
	    			 item.state = 1 ? '是':'否';
	    			 item.notNull = true ? '可为空':'不可为空';
	    			 filedDefaultArr[0].children.push(item);
	    		 });
	    	 }
	     },
	     error: function (data) {
	    	 mini.alert('失败');
	    	 console.log(data);
	     }
	 });
}
//提示信息
function showTips() {
    mini.showTips({
        content: "删除成功",
        state: "success",
        x: "center",
        y: "center",
        timeout: 1000
    });
}